package com.ibm.spatiotemp.datamodel.datatype.request;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.source.GPSDataSouceFactory;
import com.ibm.spatiotemp.source.GPSDataSource;

public class RequestPartitioner {

	public static Logger logger = Logger.getLogger(RequestPartitioner.class);
	public static Collection<Request> partitionRequestByTimeScale(Request orgrequest, long timescale)
	{
		 Collection<Request> reqlist = new LinkedList<Request>();
		 if(orgrequest instanceof BuildIdxRequest){
			 BuildIdxRequest req = (BuildIdxRequest)orgrequest;
				GPSDataSource dsrc = GPSDataSouceFactory.getGPSDataSource(req.getDatasrcid());
				long startts = req.getStartts() < dsrc.getMostEarlyTimeStamp() ?
						dsrc.getMostEarlyTimeStamp():req.getStartts();
//				long startts = req.getStartts();
				long endts = req.getEndts();
				
				startts = ((long)(startts/timescale))*((long)timescale);
				long curts = startts;
				while(curts < endts)
				{
					BuildIdxRequest curreq = (BuildIdxRequest) req.clone();
					curreq.setStartts(curts);
					curreq.setEndts(curts + timescale);
					reqlist.add(curreq);
					curts += timescale;
				}
		 }
		 else if(orgrequest instanceof TSBuildIdxRequest)
		{
			TSBuildIdxRequest req = (TSBuildIdxRequest)orgrequest;
			GPSDataSource dsrc = GPSDataSouceFactory.getGPSDataSource(req.getDatasrcid());
			long startts = req.getStartts() < dsrc.getMostEarlyTimeStamp() ?
					dsrc.getMostEarlyTimeStamp():req.getStartts();
//			long startts = req.getStartts();
			long endts = req.getEndts();
			
			startts = ((long)(startts/timescale))*((long)timescale);
			long curts = startts;
			while(curts < endts)
			{
				TSBuildIdxRequest curreq = (TSBuildIdxRequest) req.clone();
				curreq.setStartts(curts);
				curreq.setEndts(curts + timescale);
				reqlist.add(curreq);
				curts += timescale;
			}
		}
		else if(orgrequest instanceof QueryRequest)
		{
			QueryRequest req = (QueryRequest)orgrequest;
			long startts = req.getStartts();
			long endts = req.getEndts();
			
			startts = ((long)(startts/timescale))*((long)timescale);
			long curts = startts;
			while(curts < endts)
			{
				QueryRequest curreq = (QueryRequest) req.clone();
				curreq.setStartts(curts);
				curreq.setEndts(curts + timescale);
				reqlist.add(curreq);
				curts += timescale;
			}
		}
		else
		{
			logger.error("not supported partition request");
		}
		return reqlist;
	}
}
